import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './assets/css/global.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

// 创建应用实例
const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 添加请求拦截器
import axios from 'axios'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = import.meta.env.VITE_APP_API_URL || '/api'
axios.interceptors.request.use(
  config => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (userInfo.token) {
      config.headers['Authorization'] = `Bearer ${userInfo.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        // 未授权，清除用户信息并跳转到登录页
        localStorage.removeItem('userInfo')
        router.push('/login')
        ElMessage.error('登录已过期，请重新登录')
      } else if (error.response.status === 403) {
        ElMessage.error('没有权限访问该资源')
      } else if (error.response.status === 500) {
        ElMessage.error('服务器错误，请稍后再试')
      } else {
        ElMessage.error(error.response.data.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查您的网络连接')
    }
    return Promise.reject(error)
  }
)

app.config.globalProperties.$http = axios

// 使用插件
app.use(router)
app.use(store)
app.use(ElementPlus, {
  locale: zhCn, // 设置语言为中文
})

// 挂载应用
app.mount('#app')
